package com.dongdong.zhuangji.utils.imageUtils;

import javax.imageio.ImageIO;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;

import com.dongdong.zhuangji.entity.dto.ReceiptStatementPile;
import com.dongdong.zhuangji.utils.DateToDayTime;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class InsertIntoExistingExcel {
    public static void main(String[] args) {
        ReceiptStatementPile receiptStatementPile = new ReceiptStatementPile();
        receiptStatementPile.setPileNumber("P001");
        receiptStatementPile.setMeasurementPart("桩孔灌注桩"+receiptStatementPile.getPileNumber());
        receiptStatementPile.setDate(new Date());
        receiptStatementPile.setCasingTopElevation(100.0);
        receiptStatementPile.setCasingBottomElevation(90.0);
        receiptStatementPile.setOrificeElevation(95.0);
        receiptStatementPile.setHoleBottomElevation(70.0);
        receiptStatementPile.setSoilDepth(10.0);
        receiptStatementPile.setSandyGravelLayerDepth(5.0);
        receiptStatementPile.setSandyMudstoneDepth(3.0);
        receiptStatementPile.setCasingWallThickness(2);
        receiptStatementPile.setCasingInnerDiameter(161);
        receiptStatementPile.setHoleDiameter(150);
        receiptStatementPile.setHoleDepth(20.0);
        receiptStatementPile.setCasingLength(10.0);

        String excelPath = "D:\\devtool\\zhuangji\\桩基混凝浇筑记录.xlsx";
        creatReceiptStatementPileTable(excelPath,receiptStatementPile);
    }

    public static void creatReceiptStatementPileTable(String excelPath,ReceiptStatementPile receiptStatementPile) {




        try (FileInputStream fileIn = new FileInputStream(new File(excelPath));
             Workbook workbook = new XSSFWorkbook(fileIn)) {

            creatReceiptStamentPileTable(receiptStatementPile, workbook);

            try (FileOutputStream fileOut = new FileOutputStream(new File(excelPath))) {
                workbook.write(fileOut);
            }
            System.out.println("Excel 文件已更新：" + excelPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void creatReceiptStamentPileTable(ReceiptStatementPile receiptStatementPile, Workbook workbook) {
        saveToExcel(workbook, "Sheet4", "B3", receiptStatementPile.getMeasurementPart());//"桩孔灌注桩"+
        DateToDayTime dateToDayTime = new DateToDayTime();
        saveToExcel(workbook, "Sheet4", "D3", dateToDayTime.toLoaclDays(receiptStatementPile.getDate()) );//"2025年5月7日"
        byte[] imageBytes = generateImage(receiptStatementPile);
        insertImageToExcel(workbook, imageBytes, "Sheet4", 3, 1);
    }

    public static byte[] generateImage(ReceiptStatementPile receiptStatementPile) {
        // 原分辨率
        double originalDpi = 72;
        // 提高后的分辨率
        double newDpi = 600;
        // 计算比例
        double ratio = newDpi / originalDpi;

        int width = (int) (16.7 / 2.54 * newDpi);
        int height = (int) (16.25 / 2.54 * newDpi);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();

        // 开启抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 高质量字体渲染
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 设置线条粗细
        float lineThickness = (float) (1 * ratio);
        g2d.setStroke(new BasicStroke(lineThickness));

        //g2d.setColor(Color.WHITE);
        //g2d.fillRect(0, 0, width, height);

        // 使用更深的颜色
        g2d.setColor(Color.red);


        int rectX = (int) (100 * ratio);
        int rectY = (int) (50 * ratio);
        int rectWidth = (int) (100 * ratio);
        int rectHeight = (int) (210 * ratio);
        g2d.drawRect(rectX, rectY, rectWidth, rectHeight);

        int lineX1 = (int) (30 * ratio);
        int lineY1 = (int) (80 * ratio);
        int lineX2 = lineX1 + (int) (65 * ratio);
        int lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);
//----------------------------------------------------
        g2d.setFont(new Font("宋体", Font.PLAIN, (int) (11 * ratio)));

        DecimalFormat df = new DecimalFormat("0.000");
        String text = "土层"+df.format(receiptStatementPile.getSoilDepth()) +"m";
        int textX = (int) (220 * ratio);
        int textY = (int) (120 * ratio);
        g2d.drawString(text, textX, textY);
        text = "砂卵石层"+df.format(receiptStatementPile.getSandyGravelLayerDepth())+"m";
        textY = (int) (205 * ratio);
        g2d.drawString(text, textX, textY);
        receiptStatementPile.setSandyMudstoneDepth(Double.parseDouble(df.format(receiptStatementPile.getHoleDepth()))-Double.parseDouble(df.format(receiptStatementPile.getSoilDepth()))-Double.parseDouble(df.format(receiptStatementPile.getSandyGravelLayerDepth())));
        text = "砂质泥岩"+df.format(receiptStatementPile.getSandyMudstoneDepth())+"m";
        textY = (int) (325 * ratio);
        g2d.drawString(text, textX, textY);

        text = "孔径："+receiptStatementPile.getHoleDiameter()+"cm";
        textX=(int) (310 * ratio);
        textY = (int) (305 * ratio);
        g2d.drawString(text, textX, textY);

        text = "孔深："+df.format(receiptStatementPile.getHoleDepth())+"m";
        textY = (int) (325 * ratio);
        g2d.drawString(text, textX, textY);
        DecimalFormat df1=new DecimalFormat("0");
        text = "护筒长度："+df1.format(receiptStatementPile.getCasingLength())+"m";
        textY = (int) (345 * ratio);
        g2d.drawString(text, textX, textY);


        lineX1 = (int)(230 * ratio);
        lineX2 = lineX1;
        lineY2 = (int)(105* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineY1 = (int)(125* ratio);
        lineY2 = (int)(190* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineY1 = (int)(210* ratio);
        lineY2 = (int)(310* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineY1 = (int)(330* ratio);
        lineY2 = (int)(380* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);


        lineX1=(int)(227* ratio);
        lineY1 = (int)(375* ratio);
        lineX2=(int)(230* ratio);
        lineY2 = (int)(380* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1=(int)(233* ratio);
        lineY1 = (int)(375* ratio);
        lineX2=(int)(230* ratio);
        lineY2 = (int)(380* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1=(int)(227* ratio);
        lineX2=(int)(233* ratio);

        lineY1 = (int)(245* ratio);
        lineY2 = (int)(255* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);
        lineY1 = (int)(255* ratio);
        lineY2 = (int)(245* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineY1 = (int)(145* ratio);
        lineY2 = (int)(155* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);
        lineY1 = (int)(155* ratio);
        lineY2 = (int)(145* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1=(int)(227* ratio);
        lineX2=(int)(230* ratio);
        lineY1 = (int)(85* ratio);
        lineY2 = (int)(80* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);
        lineX1=(int)(230* ratio);
        lineX2=(int)(233* ratio);
        lineY1 = (int)(80* ratio);
        lineY2 = (int)(85* ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);


//-----------------------------------------
         lineX1 = (int) (30 * ratio);
         lineY1 = (int) (80 * ratio);
         lineX2 = lineX1 + (int) (65 * ratio);
         lineY2 = lineY1;

        lineX1 = lineX2;
        lineY1 = lineY2;
        lineX2 = lineX1;
        lineY2 = lineY1 + (int) (300 * ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1 = lineX2;
        lineY1 = lineY2;
        lineX2 = lineX1 + (int) (110 * ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1 = lineX2;
        lineY1 = lineY2;
        lineX2 = lineX1;
        lineY2 = lineY1 - (int) (300 * ratio);
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1 = lineX2;
        lineY1 = lineY2;
        lineX2 = lineX1 + (int) (55 * ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineX1 = lineX1+(int)(5 * ratio);
        lineY1 = (int)(150* ratio);
        lineX2 = lineX1 + (int) (50* ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineY1 = (int)(250* ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        lineY1 = (int)(380* ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);


        lineX1 = (int)(350* ratio);
        lineY1 =  (int) (165 * ratio);
        lineX2 =(int)(420* ratio);
        lineY2=  (int) (165 * ratio);;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        int circleX = (int) (300 * ratio);
        int circleY = (int) (140 * ratio);
        int circleRadius = (int) (25 * ratio);
        g2d.drawOval(circleX, circleY, 2 * circleRadius, 2 * circleRadius);




         text = "护筒顶"+receiptStatementPile.getCasingTopElevation()+"m";
         textX = (int) (110 * ratio);
         textY = (int) (35 * ratio);
        g2d.drawString(text, textX, textY);

        // 绘制多段线
        int[] polylineXPoints = {
                (int) (130 * ratio), (int) (120 * ratio), (int) (110 * ratio), (int) (190 * ratio)
        };
        int[] polylineYPoints = {
                (int) (40 * ratio), (int) (50 * ratio), (int) (40 * ratio), (int) (40 * ratio)
        };
       // g2d.setColor(Color.BLUE.darker()); // 使用更深的蓝色
        g2d.drawPolyline(polylineXPoints, polylineYPoints, polylineXPoints.length);

        text = "成孔隐蔽收方：";
        textX = (int) (30 * ratio);
        textY = (int) (20 * ratio);
        g2d.drawString(text, textX, textY);
        text = "孔口"+df.format(receiptStatementPile.getOrificeElevation())+"m";
        textX = (int) (30 * ratio);
        textY = (int) (65 * ratio);
        g2d.drawString(text, textX, textY);

        text = receiptStatementPile.getPileNumber()+"桩基成孔土石成分柱状图";
        textX = (int) (80 * ratio);
        textY = (int) (400 * ratio);
        g2d.drawString(text, textX, textY);


        text = "壁厚"+receiptStatementPile.getCasingWallThickness()+"cm";
        textX = (int) (360 * ratio);
        textY = (int) (160 * ratio);
        g2d.drawString(text, textX, textY);
        text = "内径"+(receiptStatementPile.getCasingInnerDiameter())+"cm";
        textX = textX;
        textY = textY + (int) (20 * ratio);
        g2d.drawString(text, textX, textY);

        text = "钢护筒";
        textX = (int) (310 * ratio);
        textY = (int) (220 * ratio);
        g2d.drawString(text, textX, textY);

        lineX1 = textX-(int) (10 * ratio);
        lineY1 = textY + (int) (10 * ratio);
        lineX2 = lineX1 + (int) (55 * ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);
        lineY1 = lineY1 + (int) (10 * ratio);
        lineY2 = lineY1;
        g2d.drawLine(lineX1, lineY1, lineX2, lineY2);

        polylineXPoints = new int[]{
                (int) (50 * ratio), (int) (40 * ratio), (int) (30 * ratio), (int) (90 * ratio)
        };
        polylineYPoints = new int[]{
                (int) (70 * ratio), (int) (80 * ratio), (int) (70 * ratio), (int) (70 * ratio)
        };
        g2d.drawPolyline(polylineXPoints, polylineYPoints, polylineXPoints.length);

        text = "护筒底"+df.format(receiptStatementPile.getCasingBottomElevation())+"m";
        textX = (int) (110 * ratio);
        textY = (int) (245 * ratio);
        g2d.drawString(text, textX, textY);

        polylineXPoints = new int[]{
                (int) (130 * ratio), (int) (120 * ratio), (int) (110 * ratio), (int) (190 * ratio)
        };
        polylineYPoints = new int[]{
                (int) (250 * ratio), (int) (260 * ratio), (int) (250 * ratio), (int) (250 * ratio)
        };
        g2d.drawPolyline(polylineXPoints, polylineYPoints, polylineXPoints.length);

        text = "桩底"+df.format(receiptStatementPile.getHoleBottomElevation())+"m";
        textY = (int) (365 * ratio);
        g2d.drawString(text, textX, textY);

        polylineXPoints = new int[]{
                (int) (130 * ratio), (int) (120 * ratio), (int) (110 * ratio), (int) (190 * ratio)
        };
        polylineYPoints = new int[]{
                (int) (370 * ratio), (int) (380 * ratio), (int) (370 * ratio), (int) (370 * ratio)
        };
        g2d.drawPolyline(polylineXPoints, polylineYPoints, polylineXPoints.length);

        g2d.dispose();

        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", bos);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void saveToExcel(Workbook workbook, String sheetName, String cellPosition, Object value) {
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workbook.createSheet(sheetName);
        }

        int colIndex = CellReference.convertColStringToIndex(cellPosition.replaceAll("\\d+", ""));
        int rowIndex = Integer.parseInt(cellPosition.replaceAll("\\D+", "")) - 1;

        Row row = sheet.getRow(rowIndex);
        if (row == null) {
            row = sheet.createRow(rowIndex);
        }

        Cell cell = row.getCell(colIndex);
        if (cell == null) {
            cell = row.createCell(colIndex);
        }

        if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        }else {
            cell.setCellValue(value+"");
        }
    }

    public static void insertImageToExcel(Workbook workbook, byte[] imageBytes, String sheetName, int startRow, int startCol) {
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            sheet = workbook.createSheet(sheetName);
        }

        XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
        if (drawing == null) {
            drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
        }

        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, startCol, startRow, startCol + 3, startRow + 11);
        int pictureIndex = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
        drawing.createPicture(anchor, pictureIndex);
    }
}